package com.scedu.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

//动态的创建对象，通过反射
public class Test08 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        //获取class对象
        Class<?> aClass = Class.forName("com.scedu.reflection.User");
        //构造一个对象;
        User o = (User) aClass.getDeclaredConstructor().newInstance();//本质上是调用了类的无参构造器
        System.out.println(o);
        //通过构造器创建对象
        Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(String.class, int.class, int.class);
        Object o1 = declaredConstructor.newInstance("张三", 3, 12);
        System.out.println(o1);
        //通过反射操作
        User user=(User) aClass.getDeclaredConstructor().newInstance();
        Field name=aClass.getDeclaredField("name");
        name.setAccessible(true); //避免private报错
        name.set(user,"李四");
        System.out.println(user.getName());
    }
}
